/*
 *@Type SocketServerUsage.java
 * @Desc
 * @Author urmsone urmsone@163.com
 * @date 2024/6/13 14:08
 * @version
 */
package example;

import controller.SocketServerController;
import dto.ActionTypeEnum;
import handler.ActionHandler;
import service.*;
import utils.ConfigLoader;
import utils.Const;
import utils.Role;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SocketServerUsage {
    public static void main(String[] args) {

        String configPath = "cluster.properties";
        try {
            List<Node> nodes = ConfigLoader.loadNodes(configPath);

            // 2. 获取当前节点ID（从环境变量或启动参数获取）
            String nodeId = "node" + 1 ;
            String currentNodeId = System.getProperty("node.id", nodeId);
            Node selfNode = nodes.stream()
                    .filter(n -> n.getNodeId().equals(currentNodeId))
                    .findFirst()
                    .orElseThrow();

            // 3. 初始化存储服务
            Store store = new NormalStore(Const.dataDir);

            // 4. 创建集群同步服务
            ClusterSyncService clusterSyncService = new ClusterSyncService(store, selfNode, nodes);

            // 5. 设置集群同步服务
            ((NormalStore) store).setClusterSyncService(clusterSyncService);

            // 6. 创建节点服务
            NodeService nodeService = new NodeService(selfNode, nodes);
            nodeService.setClusterSyncService(clusterSyncService);

            // 7. 如果是主节点，启动服务控制器
            if (selfNode.getRole() == Role.MASTER) {
                String[] addrParts = selfNode.getAddress().split(":");
                String host = addrParts[0];
                int port = Integer.parseInt(addrParts[1]);
                SocketServerController controller = new SocketServerController(
                        host, port, store, selfNode, nodes
                );
                controller.startServer();
            } else {
                // 从节点启动节点服务
                nodeService.start();
            }

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                if (clusterSyncService != null) {
                    // 关闭异步任务和线程池
                    clusterSyncService.shutdown();
                }
            }));

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
